package com.gitee.chili.leisure.util;

import com.gitee.chili.leisure.exception.BusinessException;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class InterAddress {

    /***
     * 获取外网IP
     */
    public static String internetAddress() {
        try {

            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress inetAddress;
            Enumeration<InetAddress> intelAddresses;
            while (networks.hasMoreElements()) {
                intelAddresses = networks.nextElement().getInetAddresses();
                while (intelAddresses.hasMoreElements()) {
                    inetAddress = intelAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address
                            && !inetAddress.isSiteLocalAddress()
                            && !inetAddress.isLoopbackAddress()
                            && !inetAddress.getHostAddress().contains(":")) {
                        return inetAddress.getHostAddress();
                    }
                }
            }

            return null;

        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 获取内网IP
     */
    public static String intranetAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 获取服务启动host
     */
    public static String getHost() {
        return internetAddress() == null ? intranetAddress() : internetAddress();
    }

}